<?php

namespace Desktopd\MUA;


// PeerCertStore (Stores certificates to send encrypted emails)
class PeerCertStore {
    protected $certs = array();
    private $salt;
    
    public function __construct () {
        $this->salt = openssl_random_pseudo_bytes(32);
    }
    
    protected function computeKey ($mailAddress) {
        // This is not to prevent brute-force attacks.
        return hash_hmac('sha256', $mailAddress, $this->salt);
    }
    
    public function add ($cert) {
        $cert = openssl_x509_read($cert);
        if (!is_resource($cert)) {
            return false;
        }
        
        $mailAddresses = array();
        
        $parsed = openssl_x509_parse($cert);
        
        if (isset($parsed['extensions']['subjectAltName'])) {
            $altNames = explode(',', $parsed['extensions']['subjectAltName']);
            foreach ($altNames as $altName) {
                $altName = trim($altName);
                $divided = explode(':', $altName, 2);
                if (trim(strtolower($divided[0])) === 'email' && isset($divided[1])) {
                    $mailAddress = trim($divided[1]);
                    if (!in_array($mailAddress, $mailAddresses, true)) {
                        $mailAddresses[] = $mailAddress;
                    }
                }
            }
        } elseif (isset($parsed['subject']['emailAddress'])) {
            $mailAddresses[] = $parsed['subject']['emailAddress'];
        }
        
        $certData = '';
        openssl_x509_export($cert, $certData);
        foreach ($mailAddresses as $mailAddress) {
            $this->certs[$this->computeKey($mailAddress)] = $certData;
        }
    }
    
    public function get (EmailAddress $mailAddress) {
        $mailAddress = $mailAddress->getAddress();
        $key = $this->computeKey($mailAddress);
        return isset($this->certs[$key]) ? $this->certs[$key] : '';
    }
}


// vim: ts=4 et ai

